<template>
  <el-dialog :visible="visible" :title="formTitle" width="40%" :before-close="close">
    <el-form :model="localAuthConfig" :rules="rules" ref="form">
      <el-form-item label="名称" prop="name">
        <el-input v-model="localAuthConfig.name"></el-input>
      </el-form-item>
      <el-form-item label="URL" prop="authUrl">
        <el-input v-model="localAuthConfig.authUrl"></el-input>
      </el-form-item>
      <el-form-item label="方法" prop="authMethod">
        <el-select v-model="localAuthConfig.authMethod" placeholder="请选择">
          <el-option label="GET" value="GET"></el-option>
          <el-option label="POST" value="POST"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="请求头" prop="authRequestHeaders">
        <el-input v-model="localAuthConfig.authRequestHeaders" type="textarea" rows="3"></el-input>
      </el-form-item>
      <el-form-item label="请求体" prop="authRequestBody">
        <el-input v-model="localAuthConfig.authRequestBody" type="textarea" rows="3"></el-input>
      </el-form-item>
      <el-form-item label="请求参数" prop="authRequestParams">
        <el-input v-model="localAuthConfig.authRequestParams" type="textarea" rows="3"></el-input>
      </el-form-item>
      <el-form-item label="认证请求的请求体映射规则" prop="authHeaderMapping">
        <el-input v-model="localAuthConfig.authHeaderMapping" type="textarea" rows="3"></el-input>
      </el-form-item>
      <el-form-item label="认证响应的匹配规则" prop="authResponseMapping">
        <el-input v-model="localAuthConfig.authResponseMapping" type="textarea" rows="3"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </template>
  </el-dialog>
</template>

<script>
export default {
  props: {
    authConfig: {
      type: Object,
      default: () => ({})
    },
    visible: {
      type: Boolean
    }
  },
  data() {
    return {
      localAuthConfig: { ...this.authConfig },
      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        authUrl: [{ required: true, message: '基础 URL 不能为空', trigger: 'blur' }],
        authMethod: [{ required: true, message: '请求方法不能为空', trigger: 'change' }]
      }
    };
  },
  watch: {
    authConfig: {
      deep: true,
      handler(newVal) {
        this.localAuthConfig = { ...newVal };
      }
    }
  },
  computed: {
    formTitle() {
      return this.localAuthConfig.id ? '编辑 AUTH 配置' : '新增 AUTH 配置';
    }
  },
  methods: {
    close() {
      this.localAuthConfig = {};
      this.$refs.form.clearValidate();
      this.$emit('close');
    },
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$emit('save', this.localAuthConfig);
        }
      });
    }
  }
};
</script>